import wx from '../../subwe/bridge';
import WXPage from "../../subwe/page";
import { Index } from '../../apis/index.js';
const app = getApp();
const API = new Index();
const util = require("../../utils/util");
const {
  baseUrl,
  yundianUrl
} = require("../../config");
let freeCountDownTime = null;
WXPage({
  data: {
    password: '*****',
    t: '',
    c: 0,
    deviceSn: "",
    isCtrip: false,
    productId: '',
    orderInfo: null,
    loginInfo: null,
    ruleInfo: '',
    scan: 0,
    loading: false,
    desc: '',
    showAd: 1,
    priceInfo: {},
    freeCountDown: {
      text: null,
      max: util.FREE_TIME,
      use: util.FREE_TIME
    },
    // 倒计时 剩余免费时长
    showAwardTime: true,
    tradeNo: '',
    isBlue: false,
    isSuper: false,
    phone: '',
    devInfo: {},
    imageUrl: `${app.globalData.imageUrl}/images`
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    console.log('result.js onLoad', options);
    this.setData({
      loginInfo: wx.getStorageSync('login_key'),
      isCtrip: app.globalData.isCtrip,
      showAd: wx.getStorageSync("showAd"),
      deviceSn: app.globalData.deviceSn,
      tradeNo: options.tradeno,
      isBlue: app.globalData.isBlue
    });
    if (!this.data.loginInfo) {
      await API.getLoginToken().then(res => {
        this.setData({
          loginInfo: res.result
        });
        wx.setStorageSync("login_key", res.result);
      });
    }
    await API.GetOrderInfo({
      "tradeNo": this.data.tradeNo
    }).then(res => {
      // 延长开始时间
      // if (res.result.beginAt <= res.result.createAt && res.result.feeMode === 1) {
      //   this.orderAwardTime({orderId: res.result.id, second: util.FREE_TIME})
      // }
      res.result.formatCreateAt = this.formatTime(res.result.createAt);
      res.result.formatBeginAt = this.formatTimeMinute(res.result.beginAt);
      this.setData({
        orderInfo: res.result,
        productId: res.result.productId
      });
    });

    // 获取密码
    var param = {
      "deviceSn": this.data.deviceSn,
      "productId": this.data.productId,
      "openid": this.data.loginInfo.openid
    };
    API.getPassword(param).then(res => {
      let data = res.result;
      var pwdInfo = data.password;
      if (data.useTime > 0) {
        this.setData({
          password: pwdInfo,
          t: 0,
          c: data.count
        });
      }
    });

    // 获取产品详情
    var param = {
      "productId": this.data.productId
    };
    API.GetPriceDetail(param).then(res => {
      var priceInfo = res.result;
      this.setData({
        priceInfo: priceInfo
      });
    });

    // 同步获取设备信息
    await API.getDeviceInfo({
      "deviceSn": app.globalData.deviceSn
    }).then(res => {
      let phone = res.result.prodType !== 1 ? util.ZM_PHONE_NUMBER : util.PHONE_NUMBER;
      this.setData({
        devInfo: res.result,
        showAd: res.result.isAd,
        phone: phone
      });
    });

    // this.freeCountDownFn()
  },

  formatTimeMinute(timeAt) {
    return util.formatTimeMinute(new Date(timeAt * 1000));
  },
  formatTime(timeAt) {
    return util.formatTime(new Date(timeAt * 1000));
  },
  // 归还提醒授权
  messageAlertAuthorization() {
    let tmplIds = ['NaMpuMhn9BAHZHtBOjPhGoQnfSjsWFVrfmm5IvSEOOE', 'v1bbpgpti372bs9jIzT9KMN_66ZGjf9WvCTtpK4ObwA'];
    let countdownSecond = 60 * 60 * 3; // 单位：秒
    let that = this;
    if (that.data.orderInfo.feeMode === 2) {
      countdownSecond = that.data.priceInfo.useDuration * 60;
    }
    // wx.requestSubscribeMessage({
    //   tmplIds,
    //   success(res) {
    //     let params = {
    //       orderId: that.data.orderInfo.id,
    //       templateId: '',
    //       countdownSecond
    //     };
    //     let acceptTemIds = [];
    //     for (let key in res) if (key !== 'errMsg') if (res[key] === 'accept') {
    //       acceptTemIds.push(key);
    //       params.templateId = key;
    //       API.orderRemindRss(params).then(res => {
    //         console.log(res);
    //       });
    //     }
    //     params.templateId = acceptTemIds;
    //     if (acceptTemIds.length === 0) return;
    //     console.log(res);
    //     wx.showModal({
    //       title: '提示',
    //       content: countdownSecond / 3600 + '小时后，归还通知提醒',
    //       showCancel: false,
    //       success(res) {
    //         if (res.confirm) {
    //           console.log('用户点击确定');
    //         } else if (res.cancel) {
    //           console.log('用户点击取消');
    //         }
    //       }
    //     });
    //   },
    //   fail(err) {
    //     console.log("requestSubscribeMessage-err", err);
    //   }
    // });
  },
  // 倒计时
  freeCountDownFn: function () {
    clearInterval(freeCountDownTime);
    freeCountDownTime = setInterval(() => {
      let {
        text,
        max,
        use
      } = this.data.freeCountDown;
      if (use <= 0) return clearInterval(freeCountDownTime);
      text = util.secondToTime(use--);
      this.setData({
        freeCountDown: {
          text,
          max,
          use
        }
      });
    }, 1000);
  },
  // 结束订单，结束使用
  closeOrder: function () {
    var that = this;
    wx.showModal({
      title: '小电温馨提示',
      content: '充电结束后，请点击“立即归还”即可结束本次使用。小电速充祝您旅途愉快，欢迎下次光临!',
      cancelText: '继续使用',
      cancelColor: '#D3D3D3',
      confirmText: '立即归还',
      confirmColor: '#FF0000',
      success(res) {
        if (res.confirm) {
          var param = {
            "deviceSn": that.data.deviceSn,
            "productId": that.data.orderInfo.productId,
            "openid": that.data.loginInfo.openid,
            "tradeNo": that.data.orderInfo.tradeNo
          };
          API.closeOrder(param).then(res => {
            wx.redirectTo({
              url: '/pages/orderDetail/orderDetail?settMoney=' + res.result.settMoney + '&useTime=' + res.result.useTime + '&returnMoney=' + res.result.returnMoney + '&productId=' + that.data.orderInfo.productId + '&deviceSn=' + that.data.orderInfo.deviceSn
            });
          });
        } else if (res.cancel) {}
      }
    });
  },
  // 重置密码
  resetPassword: function () {
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    });
    var param = {
      "deviceSn": this.data.deviceSn,
      "productId": this.data.productId,
      "openid": this.data.loginInfo.openid,
      "tradeNo": this.data.orderInfo.tradeNo
    };
    API.resetPassword(param).then(res => {
      var data = res.result;
      var pwdInfo = data.password;
      this.setData({
        password: pwdInfo,
        t: 0,
        c: data.count
      });
    });
    wx.hideLoading();
  },
  showPwdCount: function (c) {
    wx.showModal({
      title: '还有 ' + c + ' 次刷新密码机会'
    });
  },
  // 故障申报
  handleReport: function () {
    var deviceSn = this.data.deviceSn;
    wx.navigateTo({
      url: '/pages/report/report?deviceSn=' + deviceSn
    });
  },
  onShow: function (e) {
    if (!this.data.isBlue) {
      // wx.playBackgroundAudio({
      //   dataUrl: 'https://zmapi.cnman.cn/password.mp3'
      // });
    }
  },
  // 联系客服
  openService: function () {
    wx.showActionSheet({
      itemList: ['使用帮助', '联系客服'],
      success: function (res) {
        if (res.tapIndex === 0) {
          wx.navigateTo({
            url: '/pages/mine/help/help' // 使用帮助
          });
        }

        if (res.tapIndex === 1) {
          wx.makePhoneCall({
            phoneNumber: this.data.phone
          });
        }
      },
      fail: function (res) {
        console.log(res.errMsg);
      }
    });
  },
  onScan() {
    wx.scanCode({
      success: res => {
        var result = res.result;
        let q = decodeURIComponent(result);
        app.globalData.deviceSn = util.getQueryString(q, "dev");
        let pcl = util.getQueryString(q, "pcl");
        if (q.includes('yundian') || pcl === '10041') {
          app.globalData.apiUrl = yundianUrl ? yundianUrl : 'https://gmzfb.cnman.cn/v1/wx/';
          app.globalData.isZm = false;
        } else if (q.includes('blue.chinaman.ink')) {
          // 二代线
          app.globalData.apiUrl = baseUrl ? baseUrl : 'https://sczfb.cnman.cn/v1/wx/';
          app.globalData.isBlue = true;
        } else {
          app.globalData.apiUrl = baseUrl ? baseUrl : 'https://sczfb.cnman.cn/v1/wx/';
        }
        wx.redirectTo({
          url: '/pages/padline/padline'
        });
      }
    });
  },
  extendTime() {
    // 在页面中定义激励视频广告
    let videoAd = null;

    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-b5039409b7cfe1bc'
      });
      videoAd.onLoad(() => {});
      videoAd.onError(err => {});
      videoAd.onClose(res => {
        if (res && res.isEnded) {
          // 正常播放结束，可以下发游戏奖励
          this.orderAwardTime({
            orderId: this.data.orderInfo.id,
            second: util.AWARD_TIME
          });
        }
        console.log(res);
      });
    }

    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load().then(() => videoAd.show()).catch(err => {
          console.log('激励视频 广告显示失败');
        });
      });
    }
  },
  // 延长计时时长
  orderAwardTime(params) {
    API.orderAwardTime(params).then(res => {
      if (!res.result) return;
      this.data.orderInfo.beginAt = (this.data.orderInfo.beginAt ? this.data.orderInfo.beginAt : this.data.orderInfo.createAt) + params.second;
      this.updateFreeCountDown();
      console.log(res);
    });
  },
  updateFreeCountDown() {
    let {
      text,
      max,
      use
    } = this.data.freeCountDown;
    use = parseInt(this.data.orderInfo.beginAt - new Date().getTime() / 1000);
    this.setData({
      freeCountDown: {
        text,
        max,
        use
      }
    });
    this.freeCountDownFn();
    let orderInfo = this.data.orderInfo;
    orderInfo.formatBeginAt = this.formatTime(this.data.orderInfo.beginAt);
    this.setData({
      orderInfo
    });
    if (this.data.orderInfo.beginAt - this.data.orderInfo.createAt >= util.AWARD_TIME) this.setData({
      showAwardTime: false
    });
  },
  totestAd: function () {
    // wx.reportEvent("ad_10086", {});
    wx.navigateToMiniProgram({
      appId: 'wx3acaa9f56437682a',
      path: '/pages/index/index?partnerId=CD0001ZMGG01'
    });
  },
  // 足浴
  thirdPageGotoLavipeditum() {
    // wx.reportEvent("service_meituan_sanazuyu", {});
    if (this.data.devInfo.city === '武汉市') {
      wx.navigateTo({
        url: '/pages/webview/wyWebview/wyWebview'
      });
    } else if (this.data.devInfo.city === '衡阳市') {
      wx.navigateTo({
        url: '/pages/webview/eyWebview/eyWebview'
      });
    } else if (this.data.devInfo.city === '南宁市') {
      wx.navigateTo({
        url: '/pages/webview/xmNnWebview/xmNnWebview'
      });
    } else {
      wx.showToast({
        title: "目前该城市暂不支持",
        icon: "none"
      });
      return;
    }
  }
});
